package com.xsz.oa.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xsz.oa.dao.ResourceDao;
import com.xsz.oa.dao.RoleDao;
import com.xsz.oa.dao.UserDao;
import com.xsz.oa.model.entity.sys.Resource;
import com.xsz.oa.model.entity.sys.Role;
import com.xsz.oa.model.entity.sys.User;
import com.xsz.oa.model.entity.sys.Resource.ResourceType;
import com.xsz.oa.service.ResourceService;

@Service
public class ResourceServiceImpl implements ResourceService{
	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private ResourceDao resourceDao;

	

	@Override
	public List<Resource> findAll() {
		return resourceDao.findAll();
	}
	
	/**
	 * 根据用户名查找该用户拥有的权限
	 */
	public Set<String> findPermissions(String username) {
		Set<String> permissions = new HashSet<String>();
		
		User user = userDao.findByUsername(username);
		
		List<Integer> roleIds = user.getRoleIds();
		
		for (Integer roleId : roleIds) {
			Role role = roleDao.findById(roleId);
			List<Integer> resourceIds = role.getResourceIdList();
			for (Integer resourceId : resourceIds) {
				Resource resource = resourceDao.findById(resourceId);
				permissions.add(resource.getPermission());
			}
		}
		
		return permissions;
	}

	/**
	 * 根据用户名查询该用户拥有的菜单
	 */
	//TODO 是否可以更改进，提高效率
	public List<Resource> findMenus(String username) {
		List<Resource> allResource = findAll();
		List<Resource> menu = new ArrayList<Resource>();
		Set<String> permissions = findPermissions(username);
		
		for (Resource resource : allResource) {
			if (resource.isRootNode()) continue;
			
			if (resource.getType() != ResourceType.menu) continue;
			
			if (!hasPermission(permissions,resource)) continue;
			
			menu.add(resource);
		}
		
		return menu;
	}
	
	/**
	 * 是否有访问该资源的权限
	 * @param permissions
	 * @param resource
	 * @return
	 */
	//TODO 这里直接比较权限字符串  是有问题的 先这么做
	public boolean hasPermission(Set<String> permissions,Resource resource) {
		
		return permissions.contains(resource.getPermission());
	}


	
}
